<template>
	<div class="search-div">
		<div class="tools-div">
			<el-button type="success" size="small" @click="addShow">添 加</el-button>
		</div>

		<el-table :data="list" style="width: 100%">
			<el-table-column prop="specName" label="规格名称" width="180" />

			<el-table-column label="规格值" #default="scope" width="280">
				<div v-for="item in scope.row.specValue">
					{{ item.key }}：
					<span v-for="v in item.valueList">{{ v }} &nbsp;</span>
				</div>
			</el-table-column>

			<el-table-column prop="createTime" label="创建时间" />

			<el-table-column label="操作" align="center" width="280" #default="scope">
				<el-button type="primary" size="small" @click="editShow(scope.row)">
					修改
				</el-button>
				<el-button type="danger" size="small" @click="deleteById(scope.row.id)">
					删除
				</el-button>
			</el-table-column>
		</el-table>

		<el-pagination
			v-model:current-page="pageParam.pageNum"
			v-model:page-size="pageParam.pageSize"
			:page-sizes="[1, 2, 3, 5]"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			@size-change="fetchData"
			@current-change="fetchData"
		/>



        <el-dialog
			v-model="dialogVisible"
			title="添加/修改"
			width="50%"
		>	{{productSpec}}
			<el-form label-width="70px" size="small">
				<el-form-item label="规则名称">
					<el-input style="width: 100%" placeholder="规格名称" v-model="productSpec.specName" />
				</el-form-item>

				<el-form-item >
                    <!-- 每次点击该按钮，就向productSpec.specValue数组中添加一个json {} -->
					<el-button type="success" size="small" @click="addNewSpec">添加新规格</el-button>
				</el-form-item>
				
                <!-- 对productSpec.specValue json数组进行遍历 -->
                <!-- item表示数组中的每个json对象{key:xxx,valueList:xxx} -->
                <!-- index:表示当前行的索引，在删除当前行时会使用到 -->
                <el-form-item  v-for="(item,index) in productSpec.specValue">
                    <!-- 每一行，两个文本框，一个删除按钮 -->
                    <!-- 第一个文本框对应json中的key属性 -->
					<el-input style="width: 20%" placeholder="规格" v-model="item.key"/>&nbsp; &nbsp;
                    <!-- 第二个文本框对应json中的valueList -->
                    <el-input style="width: 20%" placeholder="规格值(如:白色,红色)" v-model="item.valueList" />&nbsp; &nbsp;
                    <el-button type="success" size="small" @click="deleteSpecValue(index)" >删除</el-button>
				</el-form-item>

                
				<el-row style="display:flex">
					<el-button type="primary" size="small" @click="submitDialog" >
						提交
					</el-button>
				</el-row>
			</el-form>
			
		</el-dialog>
	</div>



</template>

<script setup>
	import { ref, onMounted } from 'vue'
	import { GetProductSpecPageList,SaveProductSpec,UpdateProductSpecById,DeleteProductSpecById } from '@/api/productSpec'

	let pageParam = ref({
		pageNum: 1,
		pageSize: 3,
	})

	let total = ref(0)
	let list = ref([])

	let fetchData = async () => {
		//发起请求调用查询规格列表
		// list.value = [
		//     {id:1,specName:'小米手机',specValue:[{"key":"颜色","valueList":["白色","红色","黑色"]},{"key":"内存","valueList":["8G","18G"]}],createTime:'2023-05-06 12:40:22'}
		// ]
		let { data } = await GetProductSpecPageList(
			pageParam.value.pageNum,
			pageParam.value.pageSize
		)
		data.list.forEach(element => {
			element.specValue = JSON.parse(element.specValue)
		})
		list.value = data.list

		total.value = data.total
	}

	onMounted(() => {
		fetchData()
	})

	let productSpec = ref({
		specName: '',
		specValue: [],
	})

	let dialogVisible = ref(false)

	let addShow = () => {
		dialogVisible.value = true
		productSpec.value = {
			specName: '',
			specValue: [],
		}
	}


    let addNewSpec = ()=>{
        productSpec.value.specValue.push({})
    }

    let deleteSpecValue = (index)=>{
        //从数组中删除指定位置的元素(从json数组中的指定位置，删除一个json对象)
        productSpec.value.specValue.splice(index,1) //从指定位置开始，删除一个元素
    }

    //弹窗的提交按钮
    let submitDialog = async ()=>{

        //数据格式的转换
        //遍历json数组（  {key：xx，valueList：‘1,2,3’}   ==》  {key：xx，valueList：[1,2,3]}   ）
        //item是specValue数组中的每个json对象
        productSpec.value.specValue.forEach((item)=>{
            if(typeof item.valueList == 'string'){
                item.valueList = item.valueList.replaceAll(',',"，").split('，')
            }
        })

        //将specValue整体转成字符串， [{},{}]
        productSpec.value.specValue = JSON.stringify(productSpec.value.specValue) //将json数组转成json字符串

        if(productSpec.value.id){
            await UpdateProductSpecById(productSpec.value)
        }else{
            await SaveProductSpec(productSpec.value)
        }
        
        dialogVisible.value = false
        fetchData()

    }


    let editShow = (row)=>{
        dialogVisible.value = true
        productSpec.value = row
    }
	
	const deleteById = async id => {
	await DeleteProductSpecById(id)
        fetchData()

}
</script>

<style scoped>
	.search-div {
		margin-bottom: 10px;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 3px;
		background-color: #fff;
	}

	.tools-div {
		margin: 10px 0;
		padding: 10px;
		border: 1px solid #ebeef5;
		border-radius: 3px;
		background-color: #fff;
	}
</style>